//
//  MenuScene.m
//  SCRAP_ObjC
//
//  Created by SRL on 11/3/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "cocos2d.h"
#import "MenuScene.h"
#import "PublicSpaceScene.h"
#import "Player.h"
#import "FPoint.h"
#import "iPadAppDelegate.h"
#import "Constants.h"
#import "SoundPlayer.h"

// GameKit Session ID for app
#define SCRAPSessionID @"bluetooth3"

@implementation MenuScene
//@synthesize menuTag, size, center, players, circles, corners, currentPlayerIndex, isMoving, peerListScheduled, isStarted, gamePeerId, gameSession, schedPlayerCount, opacityLayer, maxRoundLimit, maxScoreLimit;
@synthesize menu, nextScoreItem, prevScoreItem, nextRoundItem, prevRoundItem, scoreLabel, roundLabel;
@synthesize scoreLimit, roundLimit;
@synthesize typeMenu, nextTypeItem, prevTypeItem, typeLabel;

+(id) scene
{
	MenuScene *scene = [MenuScene node];
//	[SoundPlayer playMusic:@"background_song.aac"];

	return scene;
}

-(void) updatePeerList:(ccTime)dt
{
	NSLog(@"Stuff happens?");
	if([players count] > 3 && peerListScheduled)
	{
		[self unschedule:@selector(updatePeerList:)];
		peerListScheduled = FALSE;
	}
	else if(peerListScheduled && schedPlayerCount < [players count])
	{
		Player *player = [players objectAtIndex:[players count]-1];
		CCLabel *playerLabel = [CCLabel labelWithString:player.name fontName:SCRAPFont fontSize:36];
		playerLabel.position = ccp(menu.position.x,menu.position.y-50*(schedPlayerCount+1));
		playerLabel.color = ccc3(255, 255, 255);
		
		CCLabel *fakeLabel = [CCLabel labelWithString:@"Fake Label!" fontName:SCRAPFont fontSize:36];
		//CCMenuItemLabel *playerItem = [CCMenuItemLabel itemWithLabel:playerLabel target:self selector:nil];
		[self addChild:fakeLabel];
		//[menu alignItemsVertically];
		schedPlayerCount++;
		
	}
}

//-(void) start
//{
//	//if less than 2 players don't do anything
//	if([players count] < 2)
//		//return;
////	[[CCDirector sharedDirector] runWithScene:[PublicSpaceScene scene]];
//	if(peerListScheduled)
//	{
//		[self unschedule:@selector(updatePeerList:)];
//		peerListScheduled = FALSE;
//	}
//	[self removeChild:opacityLayer cleanup:YES];
//	CCMenu *menu = (CCMenu*)[self getChildByTag:menuTag];
//	[self removeChild:menu cleanup:YES];
//	
//	//opacityLayer = [CCColorLayer layerWithColor:ccc4(30, 30, 30, 255)];
////	[self addChild:opacityLayer];
//	
//	for(int i = 0; i < [players count]; i++)
//	{
//		CCSprite *circle = (CCSprite*)[circles objectAtIndex:i];
//		[self addChild:circle];
//	}
//	isStarted = TRUE;
//}

-(void) connect
{
	//[self startPicker];
	//retrieve menu from scene
	
	//clear its children (to remove the only item in it)
	//[menu removeAllChildrenWithCleanup:YES];
	
	//create list (when bluetooth works with this scene)
	//To Do:
	// 		Make a list that is populated by connecting iPhones
	
	
	//create menu item "Start" to begin picking corners and starting the game
	//CCLabel *startLabel = [CCLabel labelWithString:@"Start Game" fontName:SCRAPFont fontSize:48];
	//startLabel.color = ccc3(255, 255, 255);
	//CCMenuItemLabel *startItem = [CCMenuItemLabel itemWithLabel:startLabel target:self selector:@selector(start)];
	
	//add and align new item(s)
	//[menu addChild:startItem];
	//[menu alignItemsVertically];
	
	//add test players as labels that are not buttons
	//for(int i = 0; i < [players count]; i++)
//	{
//		Player *player = (Player*)[players objectAtIndex:i];
//		CCLabel *playerLabel = [CCLabel labelWithString:player.name fontName:SCRAPFont fontSize:36];
//		playerLabel.color = ccc3(255, 255, 255);
//		CCMenuItemLabel *playerItem = [CCMenuItemLabel itemWithLabel:playerLabel target:self selector:nil];
//		[menu addChild:playerItem];
//		[menu alignItemsVertically];
//	}
	//peerListScheduled = TRUE;
	
	//[self schedule:@selector(updatePeerList:) interval:2];
	CCScene *ps = (CCScene*)[PublicSpaceScene scene];
	[(PublicSpaceScene*)ps setPicker:gsession];
	if (scoreMode) {
		ps = (CCScene*)[PublicSpaceScene sceneWithScoreLimit:scoreLimit];
	}
	else {
		ps = (CCScene*)[PublicSpaceScene sceneWithRoundLimit:roundLimit];
	}

	[[CCDirector sharedDirector] replaceScene:[CCFadeTRTransition transitionWithDuration:1 scene:ps]];
}

-(id) init
{
	if((self =[super init]))
	{	
		gsession = [[iPadSession alloc]init];
		
		[[CCDirector sharedDirector] setDeviceOrientation:kCCDeviceOrientationLandscapeLeft];
		scoreMode = FALSE;
		//init tags
		maxScoreLimit = 500;
		maxRoundLimit = 15;
		scoreLimit = 100;
		roundLimit = 1;
		
		//get size and center
		size = [[CCDirector sharedDirector] winSize];
		center = ccp(size.width / 2, size.height / 2);
		
		//background and opacity layer
		CCSprite *background = [CCSprite spriteWithFile:@"bkgr_ipad.png"];
		background.position = center;
		opacityLayer = [CCColorLayer layerWithColor:ccc4(60, 60, 60, 190)];
		[self addChild:background];		
		[self addChild:opacityLayer];
		
		CCSprite *logo = [CCSprite spriteWithFile:@"scraptextlogo.png"];
		logo.position = ccp(center.x + 10, center.y + 175);//475);
		logo.scale = 1.25;
		[self addChild:logo];
		
		
		//menu items
		CCSprite *connectSprite = [CCSprite spriteWithFile:@"ConnectButton.png"];
		CCSprite *connectSpriteS = [CCSprite spriteWithFile:@"ConnectButtonSelected.png"];
		CCMenuItemSprite *connectItem = [CCMenuItemSprite itemFromNormalSprite:connectSprite selectedSprite:connectSpriteS target:self selector:@selector(connect)];
		connectItem.scale = 1.25;
		
		//menu
		menu = [CCMenu menuWithItems:connectItem, nil];
		menu.position = ccp(center.x, center.y);
		[menu alignItemsVertically];
		[self addChild:menu];
		
		typeLabel = [CCLabel labelWithString:@"Round" fontName:SCRAPFont fontSize:36];
		typeLabel.position = ccp(center.x, center.y -125);
		[self addChild:typeLabel];
		
		
		
		scoreLabel = [CCLabel labelWithString:[NSString stringWithFormat:@"%i", scoreLimit] fontName:SCRAPFont fontSize:36];
		scoreLabel.position = ccp(center.x, center.y-185);
		
		roundLabel = [CCLabel labelWithString:[NSString stringWithFormat:@"%i", roundLimit] fontName:SCRAPFont fontSize:36];
		roundLabel.position = scoreLabel.position;
		[self addChild:roundLabel];
		
		CCSprite *next = [CCSprite spriteWithFile:@"right small.png"];
		CCSprite *nextSelected = [CCSprite spriteWithFile:@"right small.png"];
		nextTypeItem = [CCMenuItemSprite itemFromNormalSprite:next selectedSprite:nextSelected target:self selector:@selector(typeNext)];
		
		CCSprite *prev = [CCSprite spriteWithFile:@"left small.png"];
		CCSprite *prevSelected = [CCSprite spriteWithFile:@"left small.png"];
		prevTypeItem = [CCMenuItemSprite itemFromNormalSprite:prev selectedSprite:prevSelected target:self selector:@selector(typeNext)];
		
		typeMenu = [CCMenu menuWithItems:prevTypeItem, nextTypeItem, nil];
		[typeMenu alignItemsHorizontallyWithPadding:120];
		typeMenu.position = typeLabel.position;
		
		[self addChild:typeMenu];
		

		nextScoreItem = [CCMenuItemSprite itemFromNormalSprite:next selectedSprite:nextSelected target:self selector:@selector(scoreNext)];		
		prevScoreItem = [CCMenuItemSprite itemFromNormalSprite:prev selectedSprite:prevSelected target:self selector:@selector(scorePrev)];

		prevScoreItem.visible = FALSE;
		
		scoreMenu = [CCMenu menuWithItems:prevScoreItem, nextScoreItem, nil];
		[scoreMenu alignItemsHorizontallyWithPadding:120];
		scoreMenu.position = scoreLabel.position;
		
		[self addChild:scoreMenu];
	}
	
	return self;
}

-(void)scoreNext
{
	if(scoreMode)
	{
		scoreLimit += 10;
		bool scoreVisible = TRUE;
		if(scoreLimit >= maxScoreLimit)
		{
			scoreLimit = maxScoreLimit;
			scoreVisible = FALSE;
		}
		nextScoreItem.visible = scoreVisible;
		CGPoint spos = scoreLabel.position;
		[self removeChild:scoreLabel cleanup:YES];
		scoreLabel = [CCLabel labelWithString:[NSString stringWithFormat:@"%i", scoreLimit] fontName:SCRAPFont fontSize:36];
		scoreLabel.position = spos;
		[self addChild:scoreLabel];
	}
	else
	{
		roundLimit++;
		bool scoreVisible = TRUE;
		if(roundLimit >= maxRoundLimit)
		{
			roundLimit = maxRoundLimit;
			scoreVisible = FALSE;
		}
		nextScoreItem.visible = scoreVisible;
		CGPoint spos = roundLabel.position;
		[self removeChild:roundLabel cleanup:YES];
		roundLabel = [CCLabel labelWithString:[NSString stringWithFormat:@"%i", roundLimit] fontName:SCRAPFont fontSize:36];
		roundLabel.position = spos;
		[self addChild:roundLabel];
	}
	prevScoreItem.visible = TRUE;
}

-(void)scorePrev
{
	if(scoreMode)
	{
		scoreLimit -= 10;
		bool scoreVisible = TRUE;
		if(scoreLimit <= 50)
		{
			scoreLimit = 50;
			scoreVisible = FALSE;
		}
		prevScoreItem.visible = scoreVisible;
		CGPoint spos = scoreLabel.position;
		[self removeChild:scoreLabel cleanup:YES];
		scoreLabel = [CCLabel labelWithString:[NSString stringWithFormat:@"%i", scoreLimit] fontName:SCRAPFont fontSize:36];
		scoreLabel.position = spos;
		[self addChild:scoreLabel];
	}
	else
	{
		roundLimit--;
		bool scoreVisible = TRUE;
		if(roundLimit <= 1)
		{
			roundLimit = 1;
			scoreVisible = FALSE;
		}
		prevScoreItem.visible = scoreVisible;
		CGPoint spos = roundLabel.position;
		[self removeChild:roundLabel cleanup:YES];
		roundLabel = [CCLabel labelWithString:[NSString stringWithFormat:@"%i", roundLimit] fontName:SCRAPFont fontSize:36];
		roundLabel.position = spos;
		[self addChild:roundLabel];
	}
	nextScoreItem.visible = TRUE;
}

-(void)typeNext
{
	if(scoreMode)
	{
		scoreMode = FALSE;
		CGPoint p = typeLabel.position;
		[self removeChild:typeLabel cleanup:YES];
		typeLabel = [CCLabel labelWithString:@"Round" fontName:SCRAPFont fontSize:36];
		typeLabel.position = p;
		[self addChild:typeLabel];
		roundLabel = [CCLabel labelWithString:[NSString stringWithFormat:@"%i", roundLimit] fontName:SCRAPFont fontSize:36];
		roundLabel.position = scoreLabel.position;
		if(roundLimit > 1)
			prevScoreItem.visible = TRUE;
		else
			prevScoreItem.visible = FALSE;
		
		if(roundLimit < maxRoundLimit)
			nextScoreItem.visible = TRUE;
		else
			nextScoreItem.visible = FALSE;

		[self removeChild:scoreLabel cleanup:YES];
		[self addChild:roundLabel];
	}
	else
	{
		scoreMode = TRUE;
		CGPoint p = typeLabel.position;
		[self removeChild:typeLabel cleanup:YES];
		typeLabel = [CCLabel labelWithString:@"Score" fontName:SCRAPFont fontSize:36];
		typeLabel.position = p;
		[self addChild:typeLabel];
		scoreLabel = [CCLabel labelWithString:[NSString stringWithFormat:@"%i", scoreLimit] fontName:SCRAPFont fontSize:36];
		scoreLabel.position = roundLabel.position;
		if(scoreLimit > 50)
			prevScoreItem.visible = TRUE;
		else
			prevScoreItem.visible = FALSE;
		
		if(scoreLimit < maxScoreLimit)
			nextScoreItem.visible = TRUE;
		else
			nextScoreItem.visible = FALSE;
		[self removeChild:roundLabel cleanup:YES];
		[self addChild:scoreLabel];
	}
}

//-(BOOL) ccTouchBegan:(UITouch *)touch withEvent:(UIEvent *)event
//{	
//	CGPoint point = [touch locationInView:[touch view]];
//	CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:point];
//	float x = convertedPoint.x;
//	float y = convertedPoint.y;
//	if(currentPlayerIndex > -1 && currentPlayerIndex < [players count] && !isMoving)
//	{
//		float dist = 5000;
//		currentCircleIndex = 0;
//		for(int i = 0; i < [circles count]; i++)
//		{
//			CCSprite *c = (CCSprite*)[circles objectAtIndex:i];
//			float cdist = [self distanceBetweenTwoPoints:c.position withPointB:convertedPoint];
//			if(cdist < dist)
//			{
//				dist = cdist;
//				currentCircleIndex = i;
//			}
//		}
//		CCSprite *circle = (CCSprite*)[circles objectAtIndex:currentCircleIndex];
//		circle.position = ccp(x, y);
//		isMoving = TRUE;
//	}
//	
//	return TRUE;
//}
//
//-(BOOL) ccTouchMoved:(UITouch *)touch withEvent:(UIEvent *)event
//{
//	if(isMoving) {
//		CGPoint point = [touch locationInView:[touch view]];
//		CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:point];
//		float x = convertedPoint.x;
//		float y = convertedPoint.y;
//		if(currentPlayerIndex > -1 && currentPlayerIndex < [players count] && isMoving)
//		{
//			CCSprite *circle = (CCSprite*)[circles objectAtIndex:currentCircleIndex];
//			circle.position = ccp(x, y);
//		}
//	}
//	return TRUE;
//}
//
//-(BOOL) ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
//{
//	CGPoint point = [touch locationInView:[touch view]];	
//	CGPoint convertedPoint = [[CCDirector sharedDirector] convertToGL:point];
//	if(isMoving) {
//		if(currentPlayerIndex > -1 && currentPlayerIndex < [players count] && isMoving)
//		{
//			float x = convertedPoint.x;
//			float y = convertedPoint.y;
//			
//			CCSprite *circle = (CCSprite*)[circles objectAtIndex:currentCircleIndex];
//			Player *player = (Player*)[players objectAtIndex:currentPlayerIndex];
//			
//			CGPoint corner = [self nearestCorner:convertedPoint];
//			player.corner = corner;
//			id action = [CCMoveTo actionWithDuration:.3 position:corner];
//			id ease = [CCEaseInOut actionWithAction:action rate:.3];
//			[circle runAction:ease];
//			currentPlayerIndex++;
//			if(currentPlayerIndex >= [players count])
//			{
//				//app.players = self.players;
//				NSLog(@"switching scenes");
//				[[CCDirector sharedDirector] replaceScene:[PublicSpaceScene scene]];
//			}
//		}
//		isMoving = FALSE;
//	}
//	return TRUE;
//}
//
//-(CGPoint) nearestCorner:(CGPoint)p
//{
//	float dist = 5000;
//	CGPoint point = ccp(-1, -1);
//	for(int i = 0; i < [corners count]; i++)
//	{
//		FPoint *cornerPoint = (FPoint*)[corners objectAtIndex:i];
//		CGPoint cp = [cornerPoint toCGPoint];
//		float cdist = [self distanceBetweenTwoPoints:cp withPointB:p];
//		if(cdist < dist && [self cornerCheck:p])
//		{
//			dist = cdist;
//			point = cp;
//		}
//	}
//	return point;
//}
//
//-(BOOL) cornerCheck:(CGPoint) p
//{
//	return TRUE;
//}
//
//-(float) distanceBetweenTwoPoints:(CGPoint)a withPointB:(CGPoint)b
//{
//	CGFloat dx = b.x - a.x;
//	CGFloat dy = b.y - a.y;
//	return sqrt(dx * dx + dy * dy);
//}
//

-(void) dealloc
{
	[super dealloc];
}

@end
